/*
  Seed script to insert sample data for all models.
  It uses env vars MONGODB_URI and MONGODB_DBNAME if provided; otherwise defaults to mongodb://127.0.0.1:27017/kangxinyuan
*/

const mongoose = require('mongoose');
const requireAll = require('require-all');

async function connect() {
  const DEFAULT_DB_NAME = 'kangxinyuan';
  const envUri = process.env.MONGODB_URI; // e.g., mongodb://127.0.0.1:27017
  const envDbName = process.env.MONGODB_DBNAME || DEFAULT_DB_NAME;
  const mongoUri = envUri ? `${envUri.replace(/\/$/, '')}/${envDbName}` : `mongodb://127.0.0.1:27017/${envDbName}`;
  await mongoose.connect(mongoUri, { useNewUrlParser: true });
  console.log(`MongoDB connected: ${mongoUri}`);
}

function loadModels() {
  requireAll(__dirname + '/../models');
}

async function clearCollections() {
  const modelNames = mongoose.modelNames();
  for (const name of modelNames) {
    try {
      await mongoose.model(name).deleteMany({});
    } catch (e) {
      console.warn(`Failed clearing ${name}:`, e.message || e);
    }
  }
}

async function seed() {
  // Load data from JSON files
  const fs = require('fs');
  const path = require('path');
  const foodsData = JSON.parse(fs.readFileSync(path.join(__dirname, '../data/foods.json'), 'utf8'));
  const sportsData = JSON.parse(fs.readFileSync(path.join(__dirname, '../data/sports.json'), 'utf8'));

  // Users
  const User = mongoose.model('User');
  await User.insertMany([
    { openid: 'openid_user_1', username: '小明', avatar: '/uploads/a.png', gender: 1, height: 175, weight: 70, target: 68, age: 25 },
    { openid: 'openid_user_2', username: '小红', avatar: '/uploads/b.png', gender: 2, height: 165, weight: 55, target: 52, age: 23 },
  ]);

  // AdminUser (password will be hashed by schema setter)
  const AdminUser = mongoose.model('AdminUser');
  await AdminUser.insertMany([
    { username: 'admin', avatar: '/uploads/admin.png', password: 'admin123' },
    { username: 'editor', avatar: '/uploads/editor.png', password: 'editor123' },
  ]);

  // Food - use data from JSON file
  const Food = mongoose.model('Food');
  await Food.insertMany(foodsData);

  // Sport - use data from JSON file
  const Sport = mongoose.model('Sport');
  await Sport.insertMany(sportsData);

  // Exercise
  const Exercise = mongoose.model('Exercise');
  await Exercise.insertMany([
    { exerciseType: 'Running', frequency: 'Daily', duration: 30, username: 'Alice', avatar: '/uploads/a.png', gender: 2 },
    { exerciseType: 'Cycling', frequency: '3/week', duration: 45, username: 'Bob', avatar: '/uploads/b.png', gender: 1 },
  ]);

  // Rank
  const Rank = mongoose.model('Rank');
  await Rank.insertMany([
    { name: 'Beginner', kind: 'exercise' },
    { name: 'Intermediate', kind: 'exercise' },
    { name: 'Advanced', kind: 'exercise' },
  ]);

  // Eat
  const Eat = mongoose.model('Eat');
  await Eat.insertMany([
    {
      openid: 'openid_user_1', data: '2025-10-07', eat_score: 85, exercise: 1,
      breakfast: [ { eat_time: '08:00', unit_name: '100g', food_id: 'food_rice', eat_num: 1, unit_id: 1, eat_type: 1 } ],
      lunch: [ { eat_time: '12:30', unit_name: '100g', food_id: 'food_chicken', eat_num: 2, unit_id: 1, eat_type: 2 } ],
      dinner: [ { eat_time: '19:00', unit_name: '100g', food_id: 'food_rice', eat_num: 1, unit_id: 1, eat_type: 3 } ],
      snacks: [ { eat_time: '16:00', unit_name: '1pc', food_id: 'food_banana', eat_num: 1, unit_id: 1, eat_type: 4 } ],
      score: {
        calorie_target: 2000, fat_target: 60, carbohydrate_target: 250, protein_target: 100,
        calorie_today: 1800, fat_today: 50, carbohydrate_today: 220, protein_today: 95,
      }
    }
  ]);

  // Do
  const Do = mongoose.model('Do');
  await Do.insertMany([
    {
      openid: 'openid_user_1', exercise: 1,
      sport: [ { eat_time: '18:00', unit_name: '30min', food_id: 'sport_running', eat_num: 1, unit_id: 1, eat_type: 1, type: 1 } ],
      score: {
        first_target: 5000, second_target: 8000, third_target: 10000, fourth_target: 12000,
        first_step: 5200, second_step: 8100, third_step: 9800, fourth_step: 13000,
        first_date: '2025-10-04', second_date: '2025-10-05', third_date: '2025-10-06', fourth_date: '2025-10-07'
      }
    }
  ]);

  // Current
  const Current = mongoose.model('Current');
  await Current.insertMany([
    { name: 'version', id: '1.0.0' },
    { name: 'motd', id: 'Welcome' },
  ]);

  console.log('Seed data inserted for: User, AdminUser, Food, Sport, Exercise, Rank, Eat, Do, Current');
}

async function main() {
  try {
    await connect();
    loadModels();
    await clearCollections();
    await seed();
  } catch (e) {
    console.error('Seeding failed:', e);
    process.exitCode = 1;
  } finally {
    await mongoose.disconnect();
  }
}

main();


